export const replaceUrlParams = (url, key, value) => {
	return url.replace(new RegExp('([?&]' + key + '(?=[=&#]|$)[^#&]*|(?=#|$))'), '&' + key + '=' + encodeURIComponent(value)).replace(/^([^?&]+)&/, '$1?')
}

export const getUrlParams = (search = window.location.search) => {
	const sear = search.substring(1)
	if (!sear) {
		return {}
	}
	return JSON.parse('{"' + sear.replace(/&/g, '","').replace(/=/g, '":"') + '"}', (key, value) => key === '' ? value : decodeURIComponent(value))
}

class HistoryApi {
	pushState (url, replace = true) {
		const history = window.history
		try {
			if (replace) {
				history.replaceState({}, '', url)
			} else {
				history.pushState({}, '', url)
			}
		} catch (error) {
			window.location[replace ? 'replace' : 'assign'](url)
		}
	}
	popState (url = window.location.href) {
		const params = getUrlParams()
		Object.keys(params).forEach(key => {
			url = replaceUrlParams(url, key, '')
		})
		this.pushState(url)
	}
	router (name, value, url = window.location.href) {
		const target = replaceUrlParams(url, name, value)
		this.pushState(target)
	}
}

export default new HistoryApi()
